﻿using System;
using System.Collections.Generic;
using ZyGames.DZPocker.Model;
using ZyGames.Framework.Game.Contract;
using ZyGames.DZPocker.Bll.Logic;
using ZyGames.Framework.Common.Serialization;
using ZyGames.DZPocker.Tools;

namespace ZyGames.DZPocker.Script.CsScript.Action
{
	/// <summary>
	/// 请求附近的人牌局
	/// </summary>
	public class Action10070 : BaseAction
	{
		private int userId;
		private string _tableDataStr = "";
		private string _simpleUserDataStr = "";

		private bool result = false;
		private string log = "";
		public Action10070(HttpGet actionGetter)
			: base((short)ActionType.DZGetNearUserTableInfo, actionGetter)
		{
		}
		public override bool GetUrlElement()
		{
			if (httpGet.GetInt("UserID", ref userId))
			{
				return true;
			}
			return false;
		}

		public override bool TakeAction()
		{
			var currentGameUser = GameTable.Current.GetUser(userId);

			if (currentGameUser == null)
			{
				Tool.WriteErrorLine("消息10070玩家不存在");
				log = "获取信息有误";
				result = false;
				return true;
			}
			var areaCode = currentGameUser.CityCode;
			//if (string.IsNullOrEmpty(areaCode))
			//{
			//	Tool.WriteErrorLine("消息10070玩家不存在");
			//	log = "获取信息有误";
			//	result = false;
			//	return true;
			//}
			var _friendsTableData = new List<UserPlayingTable>();
			var friendsUserData = new List<SimpleUserData>();

			var sameAreaUsers = GameTable.Current.GetUserInAreaCode(areaCode);
			sameAreaUsers.Remove(currentGameUser);
			foreach (var user in sameAreaUsers)
			{
				var tableIds = user.Property.TableIdList;
				if (tableIds.Count > 0)
				{
					foreach (var tableId in tableIds)
					{
						var table = GameRoom.Current.GetTableData(tableId);
						if (table != null)
						{
							var leftTime = table.GetLeftTime();
							var userPlayTable = new UserPlayingTable() { TableID = table.TableId, LeftTime = leftTime, TableName = table.TableName, UserHeadIcon = user.HeadIcon, UserNickName = user.NickName, UserId = user.UserId, Sex = user.Sex, Sign = user.Sign };
							if (!_friendsTableData.Contains(userPlayTable))
							{
								_friendsTableData.Add(userPlayTable);
								break;
							}
						}
					}
				}
				else
				{
					friendsUserData.Add(new SimpleUserData() { HeadIcon = user.HeadIcon, NickName = user.NickName, UserId = user.UserId });
				}
			}
			_tableDataStr = Convert.ToBase64String(ProtoBufUtils.Serialize(_friendsTableData));
			_simpleUserDataStr = Convert.ToBase64String(ProtoBufUtils.Serialize(friendsUserData));
			result = true;
			return true;
		}

		public override void BuildPacket()
		{
			this.PushIntoStack(this.result);
			this.PushIntoStack(this.log);
			this.PushIntoStack(this._tableDataStr);
			this.PushIntoStack(this._simpleUserDataStr);
		}
	}
}
